package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.adapter.NewsAdapter;
import com.longqinuo.mycarservice.entity.News;
import com.longqinuo.mycarservice.utils.PathUtils;
import com.longqinuo.mycarservice.view.LruImageCache;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link NewsListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class NewsListFragment extends Fragment implements View.OnClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private ImageView mBack;
    private TextView mTitle;
    private ImageView mOption;
    private PullToRefreshListView mPullToRefreshListView;
    private NewsAdapter mAdapter;
    private List<News> mList;

    private static RequestQueue queue;
    private static ImageLoader imageLoader;

    private FragmentManager manager;
    private FragmentTransaction mTransaction;
    public NewsListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment NewsListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static NewsListFragment newInstance(String param1, String param2) {
        NewsListFragment fragment = new NewsListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        init();
    }
    private void init() {
        manager = getActivity().getSupportFragmentManager();
        queue = Volley.newRequestQueue(getActivity());
        LruImageCache lruImageCache = LruImageCache.instance();
        imageLoader = new ImageLoader(queue, lruImageCache);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_list, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {

        mBack = (ImageView) view.findViewById(R.id.iv_top_back);
        mBack.setOnClickListener(this);
        mTitle = (TextView) view.findViewById(R.id.tv_top_title);
        mTitle.setText("新闻资讯");
        mOption = (ImageView) view.findViewById(R.id.iv_top_option);
        mOption.setVisibility(View.INVISIBLE);
        mPullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.pull_to_refresh_news);

        mList = new ArrayList<>();
        initData();
    }

    private void initData() {
        mAdapter = new NewsAdapter(getActivity(),mList,imageLoader);
        ListView listView = mPullToRefreshListView.getRefreshableView();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mTransaction = manager.beginTransaction();
                mTransaction.add(R.id.ll_main_layout,NewsDetailFragment.newInstance(mList.get(position-1).getData(),""),"NewsDetail");
                mTransaction.addToBackStack("NewsDetail");
                mTransaction.commit();
            }
        });
        listView.setAdapter(mAdapter);
        getData();
        mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(final PullToRefreshBase<ListView> refreshView) {

                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        mList.clear();
                        requestNews();
                        mAdapter.notifyDataSetChanged();
                        mPullToRefreshListView.onRefreshComplete();
                    }
                }.execute();
            }
        });
    }
    private void getData() {    //获取新闻列表数据
        new AsyncTask<Void,Void,String>() {

            @Override
            protected String doInBackground(Void... params) {

                return requestNews();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    int showapi_res_code = jsonObject.getInt("showapi_res_code");
                    if (showapi_res_code == 0) {
                        JSONObject showapi_res_body = jsonObject.getJSONObject("showapi_res_body");
                        int ret_code = showapi_res_body.getInt("ret_code");
                        if (ret_code == 0) {
                            JSONObject pagebean = showapi_res_body.getJSONObject("pagebean");
                            JSONArray contentlist = pagebean.getJSONArray("contentlist");
                            for (int i = 0; i < contentlist.length(); i++) {
                                JSONObject o = contentlist.getJSONObject(i);
//                                Log.d("数据", "数据"+o.toString());
                                String title = o.getString("title");

                                String pubDate = o.getString("pubDate");
                                JSONArray imageurls = o.getJSONArray("imageurls");
                                String url = "http://news.xinhuanet.com/photo/2011-09/15/122034862_21n.jpg";
                                if (imageurls.length()>0) {
                                    url = imageurls.getJSONObject(0).getString("url");
                                }

                                String count = "23";

                                News n = new News(url,title,pubDate,count,o.toString());
                                mList.add(n);
                            }
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }.execute();
    }
    private String requestNews() {    //请求新闻接口
        String getData = "";
        OkHttpClient client = new OkHttpClient();
        FormBody body = new FormBody.Builder()
                .add("channelId", "5572a109b3cdc86cf39001e5")   //频道ID
                .add("channelName", "汽车最新")     //频道名字
                .add("page","1")
                .add("needContent","0")   //不需要返回正文
                .add("needHtml", "0")       //正文不为html格式
                .build();

        Request request = new Request.Builder()
                .url(PathUtils.NEWS_CHANNEL)
                .header("apikey",PathUtils.BAIDU_API_KEY)
                .post(body)
                .build();
        try {
            okhttp3.Response  response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                getData = response.body().string();
                Log.d(">>>>>Get请求", getData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getData;
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_top_back:
                manager.popBackStack();
                break;

        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
